<?php
/**
 * Created by PhpStorm.
 * User: 徐嘉宾
 * Date: 2016/8/13
 * Time: 16:29
 */
namespace app\controllers;

use app\models\Class2;
use app\models\ReadContent;
use app\models\SpeakContent;
use app\models\WriteQuestion;
use Qiniu\Auth;
use Yii;
use yii\helpers\Url;
use yii\web\Controller;
use app\models\UploadForm;
use yii\web\UploadedFile;
use Qiniu\Storage\UploadManager;

class UploadController extends Controller
{
    public $layout = "main-nofoot";
    public $callbackUrl="http://iapple.imwork.net";
    public $enableCsrfValidation = false;
    public $secreKey="tNwjxahqEvJ8Dq2_FBy3dKApecJf7sD55V9EvPz8";
    public $accessKey="F8aKdCjdCKvd_Wastox_m01WlYHyELaKKPt3ZLUj";
    public function actionUpload()
    {
        $model = new UploadForm();
        $session=\Yii::$app->session;
        $session->open();
        if (Yii::$app->request->isPost) {
            $model->file = UploadedFile::getInstance($model, 'file');

            if ($model->file && $model->validate()) {
                $model->file->saveAs('./uploadfile/' . md5($model->file->baseName."toefl!") . '.' . $model->file->extension);
                $session['imgurl']='./uploadfile/' . md5($model->file->baseName."toefl!") . '.' . $model->file->extension;
                echo "上传成功";
            }else
            {
                echo "非法文件";
                die();
            }
        }

        return $this->renderPartial('upload', ['model' => $model]);
    }

    public function actionDirectionupload()
    {
        $model = new UploadForm();
        $session=\Yii::$app->session;
        $session->open();
        if (Yii::$app->request->isPost) {
            $model->file = UploadedFile::getInstance($model, 'file');
            if ($model->file && $model->validate()) {
                $model->file->saveAs('./audio/direction/' . $session['class']."_question".$session['qnum'] . '.' . $model->file->extension);
                $session['audiourl']='@web/audio/direction/' . $session['class']."_question".$session['qnum'] . '.' . $model->file->extension;
                echo "上传成功";
            }else
            {
                echo "非法文件";
                die();
            }
        }

        return $this->renderPartial('upload', ['model' => $model]);
    }

    public function actionTopicupload()
    {
        $model = new UploadForm();
        $session=\Yii::$app->session;
        $session->open();
        if (Yii::$app->request->isPost) {
            $model->file = UploadedFile::getInstance($model, 'file');

            if ($model->file && $model->validate()) {
                $model->file->saveAs('./audio/topic_content/' . $session['class']."_question".$session['qnum'] . '.' . $model->file->extension);
                $session['audiourl']='@web/audio/topic_content/' . $session['class']."_question".$session['qnum'] . '.' . $model->file->extension;
                echo "上传成功";
            }else
            {
                echo "非法文件";
                die();
            }
        }

        return $this->renderPartial('upload', ['model' => $model]);
    }

    public function actionListenscriptupload()
    {
        $model = new UploadForm();
        $session=\Yii::$app->session;
        $session->open();
        if (Yii::$app->request->isPost) {
            $model->file = UploadedFile::getInstance($model, 'file');

            if ($model->file && $model->validate()) {
                $model->file->saveAs('./audio/listening_script/' . $session['class']."_question".$session['qnum'] . '.' . $model->file->extension);
                $session['audiourl']='@web/audio/listening_script/' . $session['class']."_question".$session['qnum'] . '.' . $model->file->extension;
                echo "上传成功";
            }else
            {
                echo "非法文件";
                die();
            }
        }

        return $this->renderPartial('upload', ['model' => $model]);
    }

    public function actionReadtipsupload()
    {
        $model = new UploadForm();
        $session=\Yii::$app->session;
        $session->open();
        if (Yii::$app->request->isPost) {
            $model->file = UploadedFile::getInstance($model, 'file');

            if ($model->file && $model->validate()) {
                $model->file->saveAs('./audio/reading_tips/' . $session['class']."_question".$session['qnum'] . '.' . $model->file->extension);
                $session['audiourl']='@web/audio/reading_tips/' . $session['class']."_question".$session['qnum'] . '.' . $model->file->extension;
                echo "上传成功";
            }else
            {
                echo "非法文件";
                die();
            }
        }

        return $this->renderPartial('upload', ['model' => $model]);
    }


    public function actionDirectionsession()
    {
        $request = \Yii::$app->request;
        $session = \Yii::$app->session;
        $id = $request->get('class2');
        $class2 = Class2::findOne($id)->name;
        $session['class'] = $class2." ".$request->get('hnum');
        $session['qnum'] = $request->get('qnum');
    }

    public function actionWriteupload()
    {
        $model = new UploadForm();
        $session=\Yii::$app->session;
        $session->open();
        if (Yii::$app->request->isPost) {
            $model->file = UploadedFile::getInstance($model, 'file');

            if ($model->file && $model->validate()) {
                $model->file->saveAs('./audio/write_url/' . $session['class']."_question".$session['qnum'] . '.' . $model->file->extension);
                $session['audiourl']='@web/audio/write_url/' . $session['class']."_question".$session['qnum'] . '.' . $model->file->extension;
                echo "上传成功";
            }else
            {
                echo "非法文件";
                die();
            }
        }

        return $this->renderPartial('upload', ['model' => $model]);
    }

    public function actionGeturl()
    {
        $session = \Yii::$app->session;
        $url = $session['audiourl']?$session['audiourl']:" ";
        unset($session['audiourl']);
        return $url;
    }

    public function actionQiniu()
    {
        //$secreKey="cQwXAgNMxmrdzfxnofIPpidZEuzrxfKY54TQhP5Z";
        //$accessKey="VeQBxWIXm_iU0VAOWpcLRZZTRXec4-_TCOdtCtej";
        $request = \Yii::$app->request;
        $class = $request->get('class');
        $policy = array(
            //'callbackUrl' => 'http://iapple.imwork.net/webgit/yii/web/?r=upload/qiniucallback',
            'callbackUrl' => $this->callbackUrl.Url::toRoute('upload/qiniucallback'),
            'callbackBody' => "filename=$(fname)&filesize=$(fsize)&class=$class&hash=$(etag)"
        );
        $auth=new Auth($this->accessKey,$this->secreKey);
        $bucket='lianxi';
        $token=$auth->uploadToken($bucket, null, 3600, $policy);
        $uploadMgr = new UploadManager();
        return $this->render('up',['up_token'=>$token]);
    }

    public function actionQiniucallback()
    {
        $request = \Yii::$app->request;
        $filename=@$request->post('filename');
        $extends=@end(explode('.',$filename));
        $filesize=@$request->post('filesize');
        $class=@$request->post('class');
        $hash=@$request->post('hash');
        if(in_array(strtolower($extends),['jpg','png','gif','bmp','wav','mp3']))
        {
            $resp = array('ret' => 'success');
            $table = explode('-',$class)[0];
            $ziduan = explode('-',$class)[1];
            $id = explode('-',$class)[2];
            if ($table =='read_content'){
                if ($ziduan=='img_url'){
                    $url = $this->domain().$hash;
                    $operate = ReadContent::findOne($id);
                    $operate->img_url = $url;
                    $operate->update();
                }
            }
            if ($table == 'speak_content'){
                $operate = SpeakContent::findOne($id);
                $url = $this->domain().$hash;
                /*
                if ($ziduan == 'img_url'){
                    $operate->img_url = $url;
                }
                if ($ziduan == 'direction'){
                    $operate->direction = $url;
                }
                if ($ziduan == 'topic_content'){
                    $operate->topic_content = $url;
                }
                if ($ziduan == 'listening_script'){
                    $operate->listening_script = $url;
                }
                if ($ziduan == 'reading_tips'){
                    $operate->reading_tips = $url;
                }*/
                $operate->$ziduan=$url;
                $operate->update();
            }
            if ($table == 'write_question'){
                $operate = WriteQuestion::findOne($id);
                $url = $this->domain().$hash;
                if ($ziduan == 'index_img_url'){
                    $operate->index_img_url = $url;
                }
                if ($ziduan == 'url'){
                    $operate->url = $url;
                }
                $operate->update();
            }
        }
        else
        {
            $resp=array('ret'=>'error','error'=>'不允许的文件类型！');
        }
        echo json_encode($resp);
    }
    public function beforeAction($action)
    {
        $session = Yii::$app->session;
        $session->open();
        if (!$session['is_admin']&&$this->action->id!="qiniucallback") {
            ?><script>alert('请登录');
    			location.href='?r=admin/login';
    		</script>
        <?php
            die;
        }
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }

    public function domain()
    {
        $domain = 'http://of4sqrj4e.bkt.clouddn.com/';
        return $domain;
    }
}